<template>
  <div class="app-container">
    <el-row style="display:flex;">
      <el-col :span="6">
        <el-table ref="roleTable" :data="roleList" @current-change="roleChange" highlight-current-row border
          style="width:255px">
          <el-table-column prop="g_id" label="" v-if="false" />
          <el-table-column prop="g_name" label="角色名称" align="center" />
        </el-table>
      </el-col>
      <el-col :span="18">
        <el-form inline>
          <el-form-item v-for="butten in buttens" :key="butten">
            <el-button size="small"
              :type="butten=='Add'?'success':butten=='Update'?'warning':butten=='Delete'?'danger':butten=='Export'?'primary':butten"
              class="promiseButton"
              :icon="butten=='Add'?'el-icon-edit':butten=='Update'?'el-icon-edit':butten=='Delete'?'el-icon-delete':butten=='Export'?'el-icon-download':butten"
              :loading="butten=='Export'?downloadLoading:false"
              @click="butten=='Add'?OpenDialog(false):butten=='Update'?update():butten=='Delete'?Delete(rows):butten=='Export'?Export():null">
              {{butten=='Add'?'添加菜单':butten=='Update'?'保存设置':butten=='Delete'?'删除菜单':butten=='Export'?'导出':butten}}
            </el-button>
          </el-form-item>
        </el-form>
        <div class="table">
          <!--引入表格组件        -->
          <table-vue v-loading="loadingTable" :columns="columns" :data="dataList" :rows="rows" :table-set="tableSet"
            @current-change="Choose" @selection-change="SelectionChange" @changeSortCallBack="changeSortCallBack"
            empty-text="暂无数据">
            <!-- #是v-slot的简写，{scope: {row, $index}}是属性对象slot双重解构，注意这里的scope要与子组件插槽绑定的属性名对应 -->
            <!-- 操作列 -->
            <template #handle="{scope: {row}}">
              <el-checkbox-group v-model="row.checkButtens" @change="checked=>checkRow(checked, row)">
                <el-checkbox :label="item" v-for="(item) in row.m_buttens" :key="item" style="margin-right:10px">
                  {{item=='Add'?'新增':item=='Update'?'更新':item=='Delete'?'删除':item=='Export'?'导出':item}}
                </el-checkbox>
              </el-checkbox-group>
            </template>
          </table-vue>
          <pagination v-show="total>0" :total="total" :page.sync="searchParams.pageIndex"
            :limit.sync="searchParams.pageSize" @pagination="handleQuery" />
        </div>
        <div>
          <el-dialog :title="dialogSet.isEdit?'编辑'+dialogSet.title:'新增'+dialogSet.title"
            :visible.sync="dialogSet.dialogVisible" :edit.sync="dialogSet.isEdit" width="700px" center>
            <new-dialog ref="newDialog" v-if="dialogSet.dialogVisible" :visible.sync="dialogSet.dialogVisible"
              @update="update" @add="add" :edit.sync="dialogSet.isEdit" :dialog-form-data="dialogFormData"
              :dialog-form="dialogForm" />
          </el-dialog>
        </div>
      </el-col>
    </el-row>
  </div>
</template>
<script>
import TableVue from "@/components/common/TableView";
import Pagination from "@/components/common/Pagination";
import newDialog from "@/components/common/newDialog";
export default {
  components: {
    TableVue,
    Pagination,
    newDialog,
  },
  data() {
    return {
      roleList: [],
      //表格相关配置
      tableSet: {
        selection: true, //是否显示多选框
        showKey: true, //显示索引列
        idColum: "m_id", //（id）主键列名称
      },
      //表格表头数据
      //Object.freeze 百度去理解 提升性能并且禁止对于该对象的属性进行修改（
      columns: Object.freeze([
        {
          sortable: true,
          attrs: {
            prop: "m_name",
            label: "菜单名称",
            width: "120",
            align: "center",
            // "show-overflow-tooltip": true,
          },
        },
        {
          //排序 若做了分页sortable:"custom"
          sortable: true,
          attrs: {
            prop: "m_sequence",
            label: "菜单顺序",
            width: "80",
            align: "center",
            // "show-overflow-tooltip": true,
          },
        },
        {
          sortable: true,
          attrs: {
            prop: "m_icon",
            label: "菜单图标资源",
            // width: "140",
            align: "center",
            // "show-overflow-tooltip": true,
          },
        },
        {
          sortable: true,
          attrs: {
            prop: "m_url",
            label: "菜单地址url",
            // width: "140",
            align: "center",
            // "show-overflow-tooltip": true,
          },
        },
        {
          slot: "handle",
          checkbox: true,
          attrs: {
            prop: "m_buttens",
            label: "菜单页面对应按钮权限",
            width: "180",
            align: "center",
            // "show-overflow-tooltip": true,
          },
        },
        {
          hidden: false,
          attrs: {
            prop: "m_state",
            label: "状态",
            width: "60",
            align: "center",
            // "show-overflow-tooltip": true,
          },
        },
      ]),
      //新增编辑弹出框相关配置
      dialogSet: {
        title: "角色菜单",
        isEdit: false,
        dialogVisible: false,
      },
      //新增编辑相关信息
      dialogFormData: {
        g_id: "",
        m_id: [],
      },
      //新增编辑form
      dialogForm: {
        labelWidth: "100px",
        inline: false,
        labelPosition: "right",
        size: "small",
        formItem: [
          {
            type: "cascader",
            label: "选择菜单",
            width: "200px",
            prop: "m_id",
            size: "small",
            isDisabled: false,
            multiple: false,
            placeholder: "请选择",
            tip: "",
            value: "",
            props: { checkStrictly: false, emitPath: true, multiple: true }, //设置单选多选模式等
            options: [],
          },
        ],
      },
      //加载表格
      loadingTable: true,
      //下载表格
      downloadLoading: false,
      dataList: [],
      searchParams: {
        pageIndex: 1,
        pageSize: 20,
        orderColumn: "", //排序字段
        orderSort: "", //排序顺序
      },
      buttens: undefined,
      //选中的行
      rows: [],
      total: 0, //查询返回的总条
      //用户下拉框数据
      menuOptions: [],
      ///多选选中列表
      checkList: [],
    };
  },
  watch: {},
  mounted: function () {
    //获取按钮权限(展示哪些按钮)
    this.buttens = this.$store.getters.buttens;
    this.getRoleList();
    // this.getMenuList();
  },

  methods: {
    load() {},
    //选中后的回调
    checkRow(checked, row) {
      var roleMenu = { m_id: "", g_id: "", m_buttens: "" };
      roleMenu.m_id = row.m_id;
      roleMenu.g_id = this.dialogFormData.g_id;
      roleMenu.m_buttens = row.checkButtens.join(",");
      let isExist = false;
      if (this.checkList.length > 0) {
        isExist = this.checkList.some((item) => {
          return roleMenu.m_id === item.m_id && roleMenu.g_id === item.g_id;
        });
      }
      if (isExist) {
        this.checkList.forEach((item) => {
          if (item.m_id == roleMenu.m_id && item.g_id == roleMenu.g_id) {
            item.m_buttens = roleMenu.m_buttens;
          }
        });
      } else {
        this.checkList.push(roleMenu);
      }
    },
    getRoleList() {
      this.baseRequest.Post("Group/List", {}).then((res) => {
        this.roleList = res.bodyList;
        if (this.roleList.length > 0) {
          this.$refs.roleTable.setCurrentRow(this.roleList[0]); //选中第一行
        }
      });
    },
    getMenuList(row) {
      var data = {};
      var params = {};
      if (row != undefined) {
        params.groupId = row.g_id;
      }
      this.baseRequest.Post("MenuGroup/List", data, params).then((res) => {
        this.loadingTable=false;
        this.dataList = res.bodyList;
        this.total = this.dataList.length;
        this.changeTree(this.dataList);
      });
    },
    getMenuListSelect() {
      this.baseRequest.Post("MenuGroup/SelectTree", {}).then((res) => {
        this.dialogForm.formItem[0].options = res.bodyList;
      });
    },
    changeTree(tree) {
      tree.forEach((temp) => {
        if (temp.m_state === 1) {
          temp.m_state = "启用";
        }
        if (temp.m_state === 0) {
          temp.m_state = "禁用";
        }
        if (temp.m_state === -1) {
          temp.m_state = "删除";
        }
        if (
          temp.m_buttens != "" &&
          temp.m_buttens != null &&
          temp.m_buttens != undefined
        ) {
          temp.m_buttens = temp.m_buttens.split(",");
        }
        var options = {};
        options.value = temp.m_id;
        options.label = temp.m_name;
        options.children = [];
        if (temp.children.length > 0) {
          this.menuOptions.push(options);
          temp.children.forEach((item) => {
            options.children.push({
              value: item.m_id,
              label: item.m_name,
            });
          });

          this.changeTree(temp.children);
        } else {
          delete options.children;
        }
      });
    },
    roleChange(row) {
  this.loadingTable=true;
      this.getMenuList(row);
      this.dialogFormData.g_id = row.g_id;
    },
    OpenDialog() {
      //置空下拉框数据
      this.menuOptions = [];
      this.getMenuListSelect();
      this.dialogSet.dialogVisible = true;
    },
    add() {
      var mIdArray = new Array();
      if (this.dialogFormData.m_id.length <= 0) {
        return;
      }
      this.dialogFormData.m_id.forEach((item) => {
        item.forEach((temp) => {
          mIdArray.push(temp);
        });
      });
      this.dialogFormData.m_id = [...new Set(mIdArray)];

      this.baseRequest
        .Post("MenuGroup/Add", {}, this.dialogFormData)
        .then((res) => {
          this.$message({
            message: "新增成功",
            type: "success",
          });
          this.dialogSet.dialogVisible = false;
          this.getMenuList({ g_id: this.dialogFormData.g_id });
        });
    },
    update() {
      if (this.checkList == undefined || this.checkList.length <= 0) {
        alert("请先设置");
        return;
      }
      this.baseRequest.Post("MenuGroup/Update", this.checkList).then((res) => {
        this.$message({
          message: "保存成功",
          type: "success",
        });
        this.getMenuList({ g_id: this.dialogFormData.g_id });
      });
    },
    Delete() {
      if (this.rows == undefined || this.rows.length <= 0) {
        this.$msgbox.alert("请选则需要删除的行");
        return;
      }
      var idList = [];
      this.rows.forEach((item) => {
        idList.push(item[this.tableSet.idColum]);
      });
      this.baseRequest
        .Post(
          "MenuGroup/Delete",
          { },
          {groupId: this.dialogFormData.g_id, idList: idList }
        )
        .then((res) => {
          this.$message({
            message: "删除成功",
            type: "success",
          });
          this.dialogSet.dialogVisible = false;
          this.getMenuList({ g_id: this.dialogFormData.g_id });
        });
    },
    handleQuery() {},
    //排序回调事件
    changeSortCallBack(props, order) {},
    //切换选中行触发
    Choose(row) {},
    //勾选行事件
    SelectionChange(rows) {
      this.rows = rows;
    },
  },
};
</script>
<style lang="scss">
.el-form-item {
  margin-bottom: 0px;
}
.app-container {
  padding: 20px;
}
</style>